import 'package:video_player/video_player.dart' ;
import 'package:flutter/material.dart' ;
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:hairen_app/server/server.dart';
import 'package:hairen_app/server/databases.dart';
import 'package:flutter_plugin/flutter_plugin.dart';
import 'intro.dart';
import 'package:hairen_app/server/state/UserInfoModel.dart';
import 'package:hairen_app/server/saveInfo.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_web_browser/flutter_web_browser.dart';
class PlayerPage extends StatefulWidget {
  final int mid;
  final Duration playTime;//播放时间
  final String setNumber;//播放集数
  PlayerPage({this.mid,this.playTime,this.setNumber="",Key key}) : super(key: key);

  @override
  _VideoAppState createState() => _VideoAppState();
}
class _VideoAppState extends State<PlayerPage> {
  VideoPlayerController _controller;

  bool _isPlaying = false;
  bool _isLoad = false; //资源加载
  bool _isLoadTime=false; //视频快进加载
  bool _isResoult = false;
  String timeLength = "0.0";
  String curTime = "0.0";
  Duration prevTime; //上一个时间
  double progress_bar = 0.0; //进度条长度
  double other_width = 0.0; //其他长度
  double height = 0.0; //屏幕高
  double width = 0.0; //屏幕宽
  double setHeight = 250.0;
  double curWidth = 0.0; //当前高度
  double curHeight = 0.0; //当前高度
  bool _isfull = false;
  Widget tabView=new Container(
    height: 40.0,
    child: new Align(
      child: new SpinKitWave(
        color: Color.fromRGBO(251, 114, 153, 1.0),
        size: 30.0,
      ),
    ),
  );
  String setNumber="";//播放集数
  String url;

  List videoList=[]; //播放列表
  List downList=[]; //下载列表

  int curVideoIndex=0; //当前播放集数

  bool istabPage=false;//防止TabPage 一直循环
  int istabPage_count=0;//防止TabPage 一直循环

  List<Map<String,String>> playTimeArr=[];
  //视频按钮隐藏时间4s 中
  int tabDisplay=10;

  Map<String,String> curVideoInfo={
    'url':'',
    'label':'',
    'title':'',
  };
  var  moveInto;
  @override
  void initState() {
    print("时间：1");
    super.initState();
    setNumber=widget.setNumber;
    getMove();
    print("时间：2");
  }

  getMove() async{
    Server.getMove(data: {'id': widget.mid.toString()}).then((ret){
      print("时间：3");
      setState(() {
        moveInto=ret['data'];
        //将播放存入播放列表
        if(moveInto['result']['m3u8']!=null){
          List lists=moveInto['result']['m3u8'];
          for(var i=0;i<lists.length;i++){
            if(lists[i]['label']==setNumber){ //判断当前播放集数
              curVideoIndex=i;
            }
            Map<String,String> info={
              'url':'',
              'label':'',
              'title':'',
            };
            info['url']=lists[i]['url'];
            info['label']=lists[i]['label'];
            info['title']="${moveInto['title']} ${lists[i]['label']}";
            videoList.add(info);
          }
          plays(videoList[curVideoIndex]['url'],curVideoIndex);

        }
        istabPage=true;
      });
    });
  }
//  @override
//  void didUpdateWidget(PlayerPage oldWidget) {
//    tabView = TabPage(curVHeight: MediaQuery.of(context).size.height-curHeight.abs(),width: width,moveInto:moveInto,plays: plays,curVideoInfo:curVideoInfo);
//  }
  saveHistory () async{
    if(curVideoInfo['title']!=""){
      DataBases db=new DataBases();
      await db.open_table();
      await   db.update_insert_view_table(mid: widget.mid,title: curVideoInfo['title'],sutitle:curVideoInfo['label'],ptime: curTime.toString());
    }
  }

  plays(url,index){

    istabPage=true;//重置
    bool isSetto=true;
    if(_controller!=null){
      _controller.pause();
      _controller.dispose();
    }
    curVideoInfo=videoList[index];

    _controller = VideoPlayerController.network(
      url,
      //      'http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_20mb.mp4',
    )
      ..addListener(() {
        _isLoad = true; //
        _isResoult = true;
        setState(() {
          timeLength = _controller.value.duration.toString().split(".")[0];
          curTime = _controller.value.position.toString().split(".")[0];
          _isPlaying = _controller.value.isPlaying;
          if(tabDisplay>0&&_isfull){
            tabDisplay-=1;
          }
          if(playTimeArr.length>2){
            playTimeArr.removeLast();
          }
          playTimeArr.insert(0,{'time':curTime});

          if(playTimeArr.length>2&&playTimeArr[0]['time']==playTimeArr[2]['time']){
            _isLoadTime=true;
          }else{
            _isLoadTime=false;
          }

        });
        if(_controller.value.position.inSeconds>1&&widget.playTime!=null&&isSetto){
          _controller.seekTo(widget.playTime);
          isSetto=false;
        }

      })
      ..initialize().then((_) {
        // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
        setState(() {});
      });
    _controller.play();
  }

  @override
  void dispose() {
      saveHistory();

      super.dispose();
      if(_controller!=null){
        _controller.dispose();
      }

    // TODO: implement dispose
  }

  void full() {
    height = MediaQuery.of(context).size.height;
    width = MediaQuery.of(context).size.width;
    progress_bar = (width * 0.5); //进度条长度
    other_width = ((width - progress_bar) / 4); //其他长度
    if (_isfull) {
      tabView = new Text('');
      curHeight = height;
      curWidth = width;
      // 全屏（隐藏status bar 和Navitation Bar）
      SystemChrome.setEnabledSystemUIOverlays([]);
      // 设置横屏
      SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft]);
      istabPage=true;
    } else {
      tabDisplay=10; //隐藏时间归零
      curHeight = setHeight;
      curWidth = width;
      // 退出全屏
      SystemChrome.setEnabledSystemUIOverlays(
          [SystemUiOverlay.bottom, SystemUiOverlay.top]);
      // 返回竖屏
      SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);

      if(istabPage&&height>width){ //防止TabPage 一直循环
        print("vvvkk:${istabPage}");
        print("高度:${MediaQuery.of(context).size.height}");
        tabView = TabPage(curVHeight: MediaQuery.of(context).size.height-curHeight.abs(),width: width,moveInto:moveInto,plays: plays,curVideoInfo:curVideoInfo);
        istabPage=false;
      }

//      if(istabPage_count==0){
//        tabView = TabPage(curVHeight: MediaQuery.of(context).size.height-curHeight.abs(),width: width,moveInto:moveInto,plays: plays,curVideoInfo:curVideoInfo);
//      }
    }
    istabPage_count+=1;
  }
  @override
  Widget build(BuildContext context) {
    print("时间：4");
    full();
    print("时间：5");
    return new DefaultTabController(
      length: 10,
      child: new Scaffold(
        backgroundColor: Color.fromRGBO(234, 234, 234, 1.0),
        body: new Column(
          children: <Widget>[
            new Center(
                child: new InkWell(
                  child: new Container(
                    height: curHeight,
                    width: curWidth,
                    color: Colors.black,
                    child: new Stack(
                      children: <Widget>[
                        new Container(
                          alignment: Alignment.center,
                          child: _isResoult
                              ? new Stack(
                            children: <Widget>[
                              new Container(
                                alignment: Alignment.center,
                                child: _controller.value.initialized
                                    ? AspectRatio(
                                  aspectRatio:
                                  _controller.value.aspectRatio,
                                  child: VideoPlayer(_controller),
                                )
                                    : Container(),
                              ),
                              _isLoadTime?new Align(
                              child: new CupertinoActivityIndicator(
                                animating: true,
                              )):new Text(""),
                              new Offstage(
                                offstage: _isLoad,
                                child: new Align(
                                  child: new CupertinoActivityIndicator(
                                    animating: true,
                                  ),
                                ),
                              ),
                            ],
                          )
                              : new Align(
                            child: new CupertinoActivityIndicator(
                              animating: true,
                            ),
                          ),
                        ), //视频播放
                        tabDisplay==0?new Text(""):new Positioned(
                            bottom: 10.0,
                            width: width,
                            child: _isResoult
                                ? new Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.center,
                              mainAxisSize: MainAxisSize.min,
                              children: <Widget>[
                                new Container(
                                  alignment: Alignment.center,
//                         color: Colors.blue,
                                  width: other_width,
                                  child: new InkWell(
                                    child: new Icon(
                                      _controller.value.isPlaying
                                          ? Icons.pause
                                          : Icons.play_arrow,
                                      color: Colors.white,
                                    ),
                                    onTap: _controller.value.isPlaying
                                        ? _controller.pause
                                        : _controller.play,
                                  ),
                                ),
                                new Container(
//                         color: Colors.orange,
                                  alignment: Alignment.center,
                                  width: other_width,
                                  child: new Text(
                                    curTime,
                                    style: new TextStyle(
                                        color: Colors.white, fontSize: 11.0),
                                  ),
                                ),
                                new Container(
                                  alignment: Alignment.topCenter,
                                  margin: EdgeInsets.only(bottom: 5.0),
                                  width: progress_bar,
                                  child: VideoProgressIndicator(
                                    _controller,
                                    allowScrubbing: true,
                                    colors: VideoProgressColors(
                                      playedColor:
                                      Color.fromRGBO(251, 114, 153, 1.0),
                                    ),
                                  ),
                                ),
                                new Container(
//                         color: Colors.blueAccent,
                                  alignment: Alignment.center,
                                  width: other_width,
                                  child: new Text(
                                    timeLength.indexOf(':')>=1?timeLength.toString():"0:00.00",
                                    style: new TextStyle(
                                        color: Colors.white, fontSize: 11.0),
                                  ),
                                ),
                                new Container(
                                  alignment: Alignment.center,
                                  width: other_width,
//                         color: Colors.orangeAccent,
                                  child: new InkWell(
                                    child: Icon(
                                      Icons.fullscreen,
                                      color: Colors.white,
                                    ),
                                    onTap: () {
                                      _isfull = !_isfull;
                                      full();
                                    },
                                  ),
                                )
                              ],
                            )
                                : new Text('')),
                        tabDisplay==0?new Text(""):new Positioned(
                            top: _isfull ? 05.0 : MediaQuery.of(context).padding.top,
                            width: width,
                            child: new Row(
                              children: <Widget>[
                                new Container(
//                         color: Colors.blue,
                                  child: IconButton(
                                      icon:
                                      Icon(Icons.arrow_back, color: Colors.white),
                                      onPressed: () {
                                        if (_isfull) {
                                          _isfull = !_isfull;
                                          full();
                                        } else {
                                          Navigator.pop(context);
                                        }
                                      }),
                                ),
                                new Container(
                                  alignment: Alignment.center,
                                  child: new Text(
                                    "${curVideoInfo['title']}",
                                    style: new TextStyle(
                                        color: Colors.white, fontSize: 15.0),
                                  ),
                                ),
                              ],
                            )),
                      ],
                    ),
                  ),
                  onTap: (){
                    tabDisplay=10;
                  },
                )),
            new Offstage(offstage: _isfull, child: tabView),
          ],
        ),
      ),
    );
  }

}

class TabPage extends StatefulWidget{
  final curVHeight;
  final width;
  final  moveInto;
  final  plays;
  final  curVideoInfo;
  TabPage({this.curVHeight,this.width,this.moveInto,this.plays,this.curVideoInfo});
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new TabPageState();
  }
}

class TabPageState extends State<TabPage>{

  PageController _Pcontroller = new PageController();


  List cateList = [
    {'name': '简介'},
    {'name': '选集'},
    {'name': '评论'},
  ];

  String url="";
  int index = 0;
  List<Widget> cateTab = <Widget>[];

  tabHover() {
    cateTab = [];
    for (var i = 0; i < cateList.length; i++) {
      var dom;
      if (i == index) {
        dom = new Expanded(
            flex: 1,
            child: new InkWell(
              child: new Container(
                alignment: Alignment.center,
                child: new Text(
                  cateList[i]['name'],
                  style:
                  new TextStyle(color: Color.fromRGBO(251, 114, 153, 1.0)),
                ),
                decoration: new BoxDecoration(
                    border: new Border(
                        bottom: new BorderSide(
                            color: Color.fromRGBO(251, 114, 153, 1.0),
                            width: 2.0))),
              ),
              onTap: () {
                setState(() {
                  this.index = i;
                  _Pcontroller.animateToPage(this.index,
                      duration: new Duration(microseconds: 100),
                      curve: Curves.easeInOut);
                });
              },
            ));
      } else {
        dom = new Expanded(
            flex: 1,
            child: new InkWell(
              child: new Container(
                alignment: Alignment.center,
                child: new Text(
                  cateList[i]['name'],
                  style:
                  new TextStyle(color: Color.fromRGBO(153, 153, 153, 1.0)),
                ),
              ),
              onTap: () {
                setState(() {
                  this.index = i;
                  _Pcontroller.animateToPage(this.index,
                      duration: new Duration(microseconds: 100),
                      curve: Curves.easeInOut);
                });
              },
            ));
      }
      cateTab.add(dom);
    }
  }
  //简介
  Widget intro(moveInto) {
    if(moveInto==null){
      return new Align(
        child: new CupertinoActivityIndicator(),
      );
    }else{
      return new Intro(moveInto);
    }

  }

  bool pisodesStatus=false;

  //选集
  Widget pisodes(moveInto) {
    if(moveInto==null){
      return new Align(
        child: new CupertinoActivityIndicator(),
      );
    }else{
      var result=moveInto['result'];
      List<Widget> m3u8List = <Widget>[];
      List<Widget> xunleiList = <Widget>[];
      if (result['m3u8'] != null) {
        for (var i = 0; i < result['m3u8'].length; i++) {
          m3u8List.add(new InkWell(
            child: Container(
              margin: EdgeInsets.only(top: 10.0, left: 15.0, right: 15.0),
              padding: EdgeInsets.all(10.0),
              decoration: new BoxDecoration(
                  color: Colors.white,
                  border: new Border.all(
                      width: 0.5, color: Color.fromRGBO(219, 219, 219, 1.0))),
              child: new Row(
                children: <Widget>[
                  new Expanded(
                    flex: 2,
                    child: new Text("${result['m3u8'][i]['label']}"),
                  ),
                  new Expanded(
                    flex: 1,
                    child: "${result['m3u8'][i]['label']}"=="${widget.curVideoInfo['label']}"
                        ? new Text(
                      '正在播放',
                      textAlign: TextAlign.right,
                      style: new TextStyle(color: Colors.redAccent),
                    )
                        : new Text(''),
                  ),
                ],
              ),
            ),
            onTap: (){
              setState(() {
                this.url="${result['m3u8'][i]['url']}";
                widget.plays(this.url,i);
              });
            },
          ));
        }
      }
      if (result['down'] != null) {
        for (var i = 0; i < result['down'].length; i++) {
          xunleiList.add(new InkWell(
            child: Container(
              margin: EdgeInsets.only(top: 10.0, left: 15.0, right: 15.0),
              padding: EdgeInsets.all(10.0),
              decoration: new BoxDecoration(
                  color: Colors.white,
                  border: new Border.all(
                      width: 0.5, color: Color.fromRGBO(219, 219, 219, 1.0))),
              child: new Column(
                children: <Widget>[
                  new Text("${result['down'][i]['label']}",style: new TextStyle(fontSize: 16.0),),
                  new Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      new FlatButton(onPressed: (){
                        FlutterPlugin.down("${result['down'][i]['url']}");
                      }, child: new Text('迅雷'),color: Theme.of(context).backgroundColor,textColor: Colors.white,),
                      new SizedBox(width: 20.0,),
                      new FlatButton(onPressed: (){
                        FlutterWebBrowser.openWebPage(url: "${result['down'][i]['url']}", androidToolbarColor: Colors.deepPurple);
                      }, child: new Text('本地'),color: Theme.of(context).backgroundColor,textColor: Colors.white,)
                    ],
                  ),
                ],
              ),
            ),
//            onTap: (){
//              setState(() {
//                FlutterPlugin.down("${result['down'][i]['url']}");
//              });
//            },
          ));
        }
      }
      return new ListView(
        padding: EdgeInsets.only(top: 0.0),
        children: <Widget>[

          new Container(
            height: 50.0,
            alignment: Alignment.center,
            child: new Row(
              crossAxisAlignment: CrossAxisAlignment.center,
               mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                new MaterialButton(color: !pisodesStatus?Color.fromRGBO(251, 114, 153, 1.0):null,onPressed: (){
                  setState(() {
                     pisodesStatus=false;
                  });
                },child: new Text('在线播放',style: new TextStyle(color: !pisodesStatus?Colors.white:null),),),
                new MaterialButton(color: pisodesStatus?Color.fromRGBO(251, 114, 153, 1.0):null,onPressed: (){
                 setState(() {
                   pisodesStatus=true;
                 });
                },child: new Text('资源下载',style: new TextStyle(color: pisodesStatus?Colors.white:null)),)
              ],
            ),
          ),
          new Offstage(
            offstage: pisodesStatus,
            child: new Column(
              children: <Widget>[
                new Container(
                  height: 20.0,
                  alignment: Alignment.centerLeft,
                  margin: EdgeInsets.only(left: 15.0, right: 15.0, top: 15.0),
                  child: new Text('播放列表'),
                ),
                new Column(
                  children: m3u8List,
                ),
              ],
            ),
          ),
          new Offstage(
            offstage: !pisodesStatus,
            child: new Column(
              children: <Widget>[
                new Container(
                  alignment: Alignment.centerLeft,
                  height: 20.0,
                  margin: EdgeInsets.only(left: 15.0, right: 15.0, top: 15.0),
                  child: new Text('下载列表 （播放卡顿可选择迅雷下载）'),
                ),
                new Column(
                  children: xunleiList,
                )
              ],
            ),
          ),
          new SizedBox(height: 20.0,),
        ],
      );
    }

  }



  Map userInfo = {};
  String token = "";
  getInfo() {
    SaveInfo.getUserToken().then((Map ret) {
      setState(() {
        userInfo = ret['userInfo'];
        token = ret['token'];
        if(token!=''){
          UserInfoModel.isLogin=true;
        }else{
          UserInfoModel.isLogin=false;
        }
      });
    });
  }

  @override
  void initState(){
    super.initState();
    tabHover();
    getInfo();
    print(widget.moveInto);
  }
  @override
  void dispose(){
    super.dispose();
    _Pcontroller.dispose();
  }


  //评论


  Widget _tabView() {
//    var curVHeight= MediaQuery.of(context).size.height-curHeight.abs();
    return  new Container(
        height: widget.curVHeight,
//        child: widget.childs(width, (height - curHeight.abs())),
        child: new Column(
          children: <Widget>[
            new Container(
              alignment: Alignment.center,
              width: widget.width,
              height: 40.0,
              decoration:
              new BoxDecoration(color: Colors.white, boxShadow: [
                new BoxShadow(
                    color: Color.fromRGBO(86, 84, 84, 0.5),
                    offset: Offset(0.0, 0.0),
                    blurRadius: 05.0,
                    spreadRadius: 0.0)
              ]),
              child: new Row(
                children: cateTab,
              ),
            ),
            new Container(
              height: widget.curVHeight - 40.0,
              child: new PageView(
                controller: _Pcontroller,
                onPageChanged: (i) {
                  setState(() {
                    this.index = i;
                  });
                  tabHover();
                },
                children: [
                  intro(widget.moveInto),
                  pisodes(widget.moveInto),
                  new Column(
                    children: <Widget>[
                      new Align(
                        child: new Text('开发中'),
                      )
                    ],
                  )
                ],
              ),
            )
          ],
        )
    );
  }


  @override
  Widget build(BuildContext context) {
    print("我是子页面");
    // TODO: implement build
    return _tabView();
  }

}